import React from 'react';
import { history } from 'umi'
import { Table, Input, Button, Form, Icon, Tooltip } from 'antd';
import { toNumber } from 'lodash';
import { useRequest, defaultFormatResult } from '@/hooks';
import { PageContainer } from '@/molecules';
import { EmployeeSelect } from '@/containers';
// import { Company, Organization, EmployeeSelect } from '@/containers';
import { Pagination, TableFilter } from '@/components';
import { getDict, getDisplayText } from '@/utils/dataDictUtil';
// import IconFont from '@/components/IconFont';
import SortableModal from '@/pages/Organization/EmployeeManage/components/SortableModal';
import { SEX, RESUME_STEP, RESUME_STATUS_LIST } from '../dictionary';
import { Link } from '../components';
import {
    renderShortDate,
    renderInterviewResumeStatus,
    renderNameWithReadFlag,
    renderInterviewTimeRange,
    renderTalentDegree
} from '../renderUtil';
import { queryInterviewAdminList } from '../service';
import { Operator } from './containers';
import styles from './List.less';

const formatObject = obj => {
    const newObj = {};
    // eslint-disable-next-line no-restricted-syntax
    for (const [key, value] of Object.entries(obj)) {
        if (value) {
            newObj[key] = value;
        }
    }
    return newObj;
};

const List = ({ form, location }) => {
    const { query } = location;
    const {
        name,
        talentName,
        dutyName,
        // talentPhone,
        // talentEmail,
        principalEmployeeCode,
        launchEmployeeCode
        // companyCode,
        // organizationCode
    } = query;
    const { getFieldDecorator } = form;
    const [sortableModalVisible, setSortableModalVisible] = React.useState(false);

    const [agreeTypeList, setAgreeTypeList] = React.useState([]); // 学历
    // 字典获取
    React.useEffect(() => {
        getDict('agreeType').then(ret => setAgreeTypeList(ret));
    }, []);

    // 查询
    const { data, loading, run } = useRequest(queryInterviewAdminList, {
        manual: true,
        ...defaultFormatResult
    });

    // 根据query查询
    const runByQuery = React.useCallback(() => {
        const { orderByField = '', talentSex, resumeStep, resumeStatus, ...rest } = query;
        run(
            formatObject({
                ...rest,
                talentSex: talentSex ? toNumber(talentSex) : '',
                resumeStep: resumeStep ? toNumber(resumeStep) : '',
                resumeStatus: resumeStatus ? toNumber(resumeStatus) : '',
                orderByField: orderByField.replace('end', '')
            })
        );
    }, [query, run]);

    // url参数变化时触发接口请求数据
    // 注：部分参数类型为数组时，统一保存为以","分隔的字符串，因此请求时需转换为数组格式
    // 注：部分参数类型为Number时，需调用toNumber转换，确保数据类型准确
    React.useEffect(() => {
        runByQuery();
    }, [runByQuery]);

    const getOrderState = field => {
        if (!query?.orderByField) return false;
        const arr = query?.orderByField.split('|');
        if (arr[0] === field) {
            return arr[1];
        }
        return false;
    };

    const getFilteredValue = (field, isNumber = true) => {
        const val = query?.[field];
        if (!val) return [];
        const arr = val.split(',');
        if (arr.length === 0) return [];
        if (isNumber) {
            return arr.map(it => toNumber(it));
        }
        return arr;
    };

    const columnsMap = {
        talentName: {
            title: '姓名',
            dataIndex: 'talentName',
            isSelected: true,
            isDisabled: true,
            className: styles.talentName,
            render: (text, record) => {
                const { readFlag, showReadFlag, resumeId, candidateId, contactId } = record;
                let nameEl = text || '--';
                if (text) {
                    nameEl = (
                        <Link
                            to={{
                                pathname: '/office/personnelManagement/recruitment/resume/detail',
                                query: { id: resumeId, candidateId, contactId }
                            }}
                        >
                            {text}
                        </Link>
                    );
                }
                return renderNameWithReadFlag(nameEl, readFlag, showReadFlag);
            }
        },
        talentSex: {
            title: '性别',
            dataIndex: 'talentSex',
            isSelected: true,
            isDisabled: true,
            width: 80,
            filteredValue: query?.talentSex?.split(',') ?? [],
            filters: SEX,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: text => getDisplayText(SEX, text) || '--'
        },
        dutyName: {
            title: '应聘岗位',
            dataIndex: 'dutyName',
            isSelected: true,
            isDisabled: true,
            render: (text, record) => {
                if (text && record?.recruitId) {
                    return (
                        <Link
                            to={{
                                pathname: '/office/personnelManagement/recruitment/demand/detail',
                                query: { id: record?.recruitId }
                            }}
                        >
                            {text}
                        </Link>
                    );
                }
                return text || '--';
            }
        },
        resumeStep: {
            title: '阶段',
            dataIndex: 'resumeStep',
            isSelected: true,
            isDisabled: true,
            width: 140,
            filteredValue: getFilteredValue('resumeStep'),
            filters: RESUME_STEP,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: (text, record) => (
                <>
                    {getDisplayText(RESUME_STEP, text)}
                    {text === 3 && record?.interviewRoundName ? `-${record?.interviewRoundName}` : ''}
                </>
            )
        },
        resumeStatus: {
            title: '状态',
            dataIndex: 'resumeStatus',
            isSelected: true,
            isDisabled: true,
            width: 80,
            filteredValue: getFilteredValue('resumeStatus'),
            filters: RESUME_STATUS_LIST,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: (text, record) =>
                renderInterviewResumeStatus(text, record?.resumeStatusHover) || record?.resumeStatusName || '--'
        },
        principalEmployeeName: {
            title: '负责人',
            dataIndex: 'principalEmployeeName',
            isSelected: true,
            render: text => text || '--'
        },
        launchEmployeeName: {
            title: '发起人',
            dataIndex: 'launchEmployeeName',
            isSelected: true,
            render: text => text || '--'
        },
        updateTime: {
            title: '更新时间',
            dataIndex: 'updateTime',
            isSelected: true,
            sortOrder: getOrderState('updateTime'),
            sorter: () => {},
            render: text => renderShortDate(text, 'MM-DD HH:mm') || '--'
        },
        organizationName: {
            title: '组织机构',
            dataIndex: 'organizationName',
            isSelected: false,
            render: (text, record) => {
                if (!text) return '--';
                return <Tooltip title={record?.fullPathOrganizationName || ''}>{text}</Tooltip>;
            }
        },
        companyName: {
            title: '行政机构',
            dataIndex: 'companyName',
            isSelected: false,
            render: text => text || '--'
        },
        talentPhone: {
            title: '手机号',
            dataIndex: 'talentPhone',
            isSelected: false,
            render: (text, record) =>
                text ? `${record?.phoneAreaCode ? `+${record?.phoneAreaCode} ` : ''}${text}` : '--'
        },
        talentEmail: {
            title: '邮箱',
            dataIndex: 'talentEmail',
            isSelected: false,
            render: text => text || '--'
        },
        interviewerEmployeeName: {
            title: '面试官',
            dataIndex: 'interviewerEmployeeName',
            isSelected: false,
            width: 180,
            render: val => {
                const split = '、';
                let ret = val;
                if (!ret) {
                    ret = '--';
                } else {
                    const arr = val.split(split);
                    const num = arr.length;
                    if (num > 2) {
                        ret = <Tooltip title={val}>{`${arr.splice(0, 2).join(split)}等${num}人`}</Tooltip>;
                    }
                }
                return ret;
            }
        },
        interviewStartTime: {
            title: '面试时间',
            dataIndex: 'interviewStartTime',
            isSelected: false,
            sortOrder: getOrderState('interviewStartTime'),
            sorter: () => {},
            render: (text, record) => renderInterviewTimeRange(text, record?.interviewEndTime) || '--'
        },
        talentDegree: {
            title: '学历',
            dataIndex: 'talentDegree',
            isSelected: false,
            width: 100,
            filteredValue: getFilteredValue('talentDegree', false),
            filters: agreeTypeList,
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: (val, record) =>
                renderTalentDegree(getDisplayText(agreeTypeList, val), record?.talentEduDetailVOList)
        }
    };

    const defaultColumns = Object.values(columnsMap);

    const [columns, setColumns] = React.useState(defaultColumns);

    const getFinalColumns = () => {
        if (columns.length === 0) return [];
        return columns
            .filter(item => item?.isSelected === true)
            .map(item => ({
                ...columnsMap[item.dataIndex],
                isSelected: item.isSelected
            }))
            .concat([
                {
                    title: '操作',
                    dataIndex: 'action',
                    isSelected: true,
                    fixed: 'right',
                    className: styles.tableAction,
                    render: (text, record) => <Operator record={record} onRefresh={runByQuery} />
                }
            ]);
    };

    const dataSource = data?.rows || [];
    const total = data?.total || 0;

    // 高级搜索展开标识
    const [advanceFold, setAdvanceFold] = React.useState(true);

    const handleRouterPush = params => {
        history.push({
            query: formatObject({
                ...query,
                ...params
            })
        });
    };

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        handleRouterPush({ pageNo: current, pageSize });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { talentSex = [], resumeStep = [], resumeStatus = [], talentDegree = [] } = filters;
        const { field, order } = sorter;
        handleRouterPush({
            talentSex: talentSex ? talentSex.join(',') : undefined,
            resumeStep: resumeStep ? resumeStep.join(',') : undefined,
            resumeStatus: resumeStatus ? resumeStatus.join(',') : undefined,
            talentDegree: talentDegree ? talentDegree.join(',') : undefined,
            orderByField: order ? `${field}|${order}` : undefined,
            pageNo: 1
        });
    };

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const { ...rest } = values;
                handleRouterPush({
                    ...rest,
                    pageNo: 1
                });
            }
        });
    };

    // 高阶条件
    const renderAdvanceCon = () => (
        <div className={styles.advanceCon} style={{ display: advanceFold ? 'none' : 'block' }}>
            <Form.Item label="姓名">
                {getFieldDecorator('talentName', {
                    initialValue: talentName
                })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)}
            </Form.Item>
            <Form.Item label="应聘岗位">
                {getFieldDecorator('dutyName', {
                    initialValue: dutyName
                })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)}
            </Form.Item>
            {/* <Form.Item label="手机号"> */}
            {/*    {getFieldDecorator('talentPhone', { */}
            {/*        initialValue: talentPhone */}
            {/*    })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)} */}
            {/* </Form.Item> */}
            {/* <Form.Item label="邮箱"> */}
            {/*    {getFieldDecorator('talentEmail', { */}
            {/*        initialValue: talentEmail */}
            {/*    })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)} */}
            {/* </Form.Item> */}
            <Form.Item label="负责人">
                {getFieldDecorator('principalEmployeeCode', {
                    initialValue: principalEmployeeCode
                })(
                    <EmployeeSelect
                        defaultInitData
                        showArrow
                        placeholder="请选择或输入"
                        allowClear
                        style={{ width: 190 }}
                        getPopupContainer={triggerNode => triggerNode.parentElement}
                    />
                )}
            </Form.Item>
            <Form.Item label="发起人">
                {getFieldDecorator('launchEmployeeCode', {
                    initialValue: launchEmployeeCode
                })(
                    <EmployeeSelect
                        defaultInitData
                        showArrow
                        placeholder="请选择或输入"
                        allowClear
                        style={{ width: 190 }}
                        getPopupContainer={triggerNode => triggerNode.parentElement}
                    />
                )}
            </Form.Item>
            {/* <Form.Item label="机构" style={{ marginRight: 8 }}> */}
            {/*    {form.getFieldDecorator('companyCode', { */}
            {/*        initialValue: companyCode */}
            {/*    })( */}
            {/*        <Company */}
            {/*            placeholder="请选择行政机构" */}
            {/*            getPopupContainer={triggerNode => triggerNode.parentElement} */}
            {/*        /> */}
            {/*    )} */}
            {/* </Form.Item> */}
            {/* <Form.Item> */}
            {/*    {form.getFieldDecorator('organizationCode', { */}
            {/*        initialValue: organizationCode */}
            {/*    })( */}
            {/*        <Organization */}
            {/*            placeholder="请选择组织机构" */}
            {/*            getPopupContainer={triggerNode => triggerNode.parentElement} */}
            {/*        /> */}
            {/*    )} */}
            {/* </Form.Item> */}
        </div>
    );

    return (
        <PageContainer>
            <Form layout="inline" onSubmit={handleSubmit}>
                <header className={styles.headerWrapper}>
                    <div className={styles.conditionWrapper}>
                        <Form.Item>
                            {form.getFieldDecorator('name', {
                                initialValue: name
                            })(
                                <Input.Search
                                    placeholder="搜索姓名、岗位、负责人、发起人"
                                    allowClear
                                    style={{ width: 260 }}
                                />
                            )}
                        </Form.Item>
                        <a onClick={() => setAdvanceFold(val => !val)}>
                            高级搜索
                            <Icon type={advanceFold ? 'caret-down' : 'caret-up'} />
                        </a>
                        <Button type="primary" style={{ marginLeft: 12 }} htmlType="submit">
                            搜索
                        </Button>
                    </div>
                    {/* <Tooltip title="自定义列表项"> */}
                    {/*    <IconFont */}
                    {/*        icon="iconsearchbar_modifyheader_icon_default" */}
                    {/*        isButton */}
                    {/*        style={{ fontSize: 20, marginRight: 12 }} */}
                    {/*        onClick={() => { */}
                    {/*            setSortableModalVisible(true); */}
                    {/*        }} */}
                    {/*    /> */}
                    {/* </Tooltip> */}
                </header>
                {renderAdvanceCon()}
            </Form>
            <Table
                className={styles.fixedAction}
                rowKey={item => `${item.arrangeId}${item.candidateId}${item.contactId}`}
                columns={getFinalColumns()}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
            <SortableModal
                title="自定义列表项"
                dataSource={columns}
                visible={sortableModalVisible}
                onCancel={() => {
                    setSortableModalVisible(false);
                }}
                onChange={(selected, allData) => {
                    setColumns(allData);
                    setSortableModalVisible(false);
                }}
            />
        </PageContainer>
    );
};

export default Form.create()(List);
